<?php
class site extends Mod
{
	public $conn;
	
	public function __construct()
	{
		$this->conn = new Sqlite();
		$this->conn->connection('crm.db');
	}
	
	public function index()
	{
		$status = isset($_GET['s']) ? Unit::safe($_GET['s']) : -1;
		$data['status'] = $status;
		//$this->render('index', $data);
		echo 'test.';
	}
	
	public function signin()
	{
		$this->render('signin');
	}
	
	public function m_signin()
	{
		$this->render('msignin');
	}
	
	public function search()
	{
		$keywords = isset($_GET['k']) ? Unit::safe($_GET['k']) : 'camelliae';
		$data['keywords'] = $keywords;
		$this->render('search', $data);
	}
	
	
	
	public function create_token()
	{
		/*while($i < 498) {
			$i ++;
			$sqlstr = "insert into user (add_time, token) values (" . time() . ",'" . rand(1001, 9998) . "')";
			$this->conn->sql = $sqlstr;
			$res = $this->conn->execute();
			var_dump($res);
		}*/
		
		
	}
	
	public function get_list()
	{
		$status = isset($_GET['s']) ? Unit::safe($_GET['s']) : -1;
		$keywords = isset($_GET['k']) ? Unit::safe($_GET['k']) : '';
		$whereStr = '';
		if ($status > -1) {
			$whereStr .= " AND `status`='$status'";
		}
		if ( ! empty($keywords)) {
			$whereStr .= " AND (`name` LIKE '%$keywords%' OR `inviter` LIKE '%$keywords%' OR `tnumber` LIKE '%$keywords%' OR `mobile` LIKE '%$keywords%' OR `token` LIKE '%$keywords%')";
		}
		$this->conn->sql = "SELECT * FROM user WHERE 1=1" . $whereStr;
		$queryData = $this->conn->rows();
		$count = $this->conn->count();
		$res = ['code' => 0, 'msg' => '返回成功', 'count' => $count];
		$res['data'] = $queryData;
		die(json_encode($res));
	}
	
	public function get_profile()
	{
		$res = ['code' => 0, 'msg' => '返回成功'];
		$token = isset($_POST['t']) ? Unit::safe($_POST['t']) : 1000;
		if (is_numeric($token) && $token > 1000 && $token < 10000) {
			$sqlstr = "SELECT * FROM user WHERE token='$token'";
			$this->conn->sql = $sqlstr;
			$queryData = $this->conn->row();
			$res['data'] = $queryData;
		}
		die(json_encode($res));
	}
	
	public function save()
	{
		$res = ['code' => 0, 'msg' => '返回成功'];
		$id = $_POST['id'];
		$field = $_POST['field'];
		$value = $_POST['value'];
		$sets = ",edit_time='" . time() . "'";
		if ($field == 'status' && $value == 1) {
			$sets .= ",confirm_time='" . time() . "'";
		}
		$sqlstr = "UPDATE user SET $field='$value'" . $sets . " WHERE id=$id";
		//$res['sql'] = $sqlstr;
		$this->conn->sql = $sqlstr;
		$exec = $this->conn->execute();
		$res['status'] = $exec['code'];
		$res['msg'] = $exec['msg'];
		die(json_encode($res));
	}
	
}